import React from "react";
import { useState, useEffect } from "react";
import { Tag } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { getTypeList, updateIssueTypeId, updateBookTypeId } from "@/redux/typeSlice";

export default function TypeSelect() {
  const dispatch = useDispatch();
  const { typeList } = useSelector((state) => state.type);
  const colorArr = ["#108ee9", "#2db7f5", "#f50", "green", "#87d068", "blue", "red", "purple"];
  const [typeContainer, setTypeContainer] = useState([]);

  const changeType = (typeValue) => {
    if (location.pathname === "/issues") {
      dispatch(updateIssueTypeId(typeValue));
    } else if (location.pathname === "/books") {
      dispatch(updateBookTypeId(typeValue));
    }
  };

  useEffect(() => {
    if (!typeList.length) {
      dispatch(getTypeList());
    }
    const typeArr = [];
    typeArr.push(
      // @ts-ignore
      <Tag
        color="magenta"
        value="all"
        key="all"
        style={{ cursor: "pointer" }}
        onClick={() => changeType("all")}
      >
        全部
      </Tag>
    );
    for (let i = 0; i < typeList.length; i++) {
      typeArr.push(
        // @ts-ignore
        <Tag
          color={colorArr[i % colorArr.length]}
          value={typeList[i]._id}
          key={typeList[i]._id}
          style={{ cursor: "pointer" }}
          onClick={() => changeType(typeList[i]._id)}
        >
          {typeList[i].typeName}
        </Tag>
      );
      setTypeContainer(typeArr);
    }
  }, [typeList]);
  return <>{typeContainer}</>;
}
